#!/bin/bash
#
# Init file for Phoebus Session Daemon
#
# chkconfig: 2345 60 20
# description: Phoebus Session Daemon
#
# processname: psd 
#


#PREFIX=/prefixdir
if [ -z ${PREFIX} ]; then
PHOEBUSBINDIR=/usr/sbin
else
PHOEBUSBINDIR=${PREFIX}/sbin
fi
CONFDIR=${PREFIX}/etc
CONFFILE=${PREFIX}/etc/phoebus/psd.conf
PHOEBUSVARDIR=${PREFIX}/var
PIDFILE=${PHOEBUSVARDIR}/run/phoebus.pid
LOGFILE=${PHOEBUSVARDIR}/log/phoebus.log
DEBUGLEVEL=9

PSD="${PHOEBUSBINDIR}/psd -c ${CONFFILE} -d ${DEBUGLEVEL} -o ${LOGFILE} -p ${PIDFILE} -B"

ERROR=0
ARGV="$@"
if [ "x$ARGV" = "x" ] ; then
    ARGS="help"
fi

for ARG in $@ $ARGS
do
    # check for pidfile
    if [ -f $PIDFILE ] ; then
        PID=`cat $PIDFILE`
        if [ "x$PID" != "x" ] && kill -0 $PID 2>/dev/null ; then
            STATUS="phoebus (pid $PID) running"
            RUNNING=1
        else
            STATUS="phoebus (pid $PID?) not running"
            RUNNING=0
        fi
    else
        STATUS="phoebus (no pid file) not running"
        RUNNING=0
    fi

    case $ARG in
    start)
        if [ $RUNNING -eq 1 ]; then
            echo "$0 $ARG: phoebus (pid $PID) already running"
            continue
        fi

        echo $PSD

        if $PSD ; then
            echo "$0 $ARG: phoebus started"
        else
            echo "$0 $ARG: phoebus could not be started"
            ERROR=3
        fi
        ;;
    stop)
        if [ $RUNNING -eq 0 ]; then
            echo "$0 $ARG: $STATUS"
            continue
        fi
        if kill $PID ; then
            echo "$0 $ARG: phoebus stopped"
        else
            echo "$0 $ARG: phoebus could not be stopped"
            ERROR=4
        fi
        ;;
    restart)
        $0 stop; echo "waiting..."; sleep 10; $0 start;
        ;;
#       if [ $RUNNING -eq 0 ]; then
#           echo "$0 $ARG: phoebus not running, trying to start"
#           if $PSD ; then
#               echo "$0 $ARG: phoebus started"
#           else
#               echo "$0 $ARG: phoebus could not be started"
#               ERROR=5
#           fi
#       else
#           if kill -HUP $PID ; then
#              echo "$0 $ARG: phoebus restarted"
#           else
#              echo "$0 $ARG: phoebus could not be restarted"
#              ERROR=6
#           fi
#       fi
#       ;;
    *)
        echo "usage: $0 (start|stop|restart|help)"
        cat <<EOF

start      - start phoebus
stop       - stop phoebus
restart    - restart phoebus if running by sending a SIGHUP or start if 
             not running
help       - this screen

EOF
        ERROR=2
    ;;

    esac

done

exit $ERROR
